#include "TcpConnection.hpp"

#include <sstream>

namespace xww
{

TcpConnection::TcpConnection(int fd)
:_sock(fd)
,_sockIO(fd)
, _localAddr(getLocalAddress())
, _peerAddr(getPeerAddress())
{

}

string TcpConnection::receive()
{
    char buf[65535];
    int ret = _sockIO.readline(buf, sizeof(buf));//读取一行数据
                                                 // 返回值ret是读取的字节数
                                                 
    return string(buf, ret);
}

void TcpConnection::send(const string & msg)
{
    if(msg.size() > 0)
        _sockIO.sendn(msg.c_str(), msg.size());
}


bool TcpConnection::isClosed() const
{
    char buf[20] = {0};
    return _sockIO.recvPeek(buf, sizeof(buf)) == 0; //如果返回值为0，表示连接已关闭
}

void TcpConnection::shutdown()
{
    _sock.shutdownWrite(); //关闭写端
}

string TcpConnection::toString() const
{
    std::ostringstream oss;
    oss << "tcp " << _localAddr.ip() << ":" << _localAddr.port()
        << " -> " << _peerAddr.ip() << ":" << _peerAddr.port();
    return oss.str();
}

//获取本地地址
//返回一个InetAddress对象，包含本地IP和端口信息
InetAddress TcpConnection::getLocalAddress() const
{
    struct sockaddr_in addr;
    memset(&addr, 0, sizeof(addr));
    socklen_t len = sizeof(addr);
    int ret = getsockname(_sock.fd(), (struct sockaddr*)&addr, &len);
    if(ret < 0) {
        perror("getsockname");
    }
    return InetAddress(addr);
}

//获取对端地址
//返回一个InetAddress对象，包含对端IP和端口信息 
InetAddress TcpConnection::getPeerAddress() const
{
    struct sockaddr_in addr;
    memset(&addr, 0, sizeof(addr));
    socklen_t len = sizeof(addr);
    int ret = getpeername(_sock.fd(), (struct sockaddr*)&addr, &len);
    if(ret < 0) {
        perror("getpeername");
    }
    return InetAddress(addr);
}

}//end of namespace xww